'use client';

import React from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { getPermissionFormSchema } from './permission-form-schema.js';

const normalizeDefaultValues = (defaultValues = {}) => ({
  name: defaultValues.name ?? '',
  displayName: defaultValues.displayName ?? '',
  resource: defaultValues.resource ?? '',
  action: defaultValues.action ?? '',
  category: defaultValues.category ?? '',
  sortOrder:
    typeof defaultValues.sortOrder === 'number'
      ? defaultValues.sortOrder
      : 0,
  description: defaultValues.description ?? '',
});

function PermissionForm({
  mode = 'create',
  defaultValues,
  onSubmit,
  onCancel,
  isSubmitting = false,
  disableName = false,
}) {
  const schema = React.useMemo(() => getPermissionFormSchema(mode), [mode]);

  const form = useForm({
    resolver: zodResolver(schema),
    defaultValues: normalizeDefaultValues(defaultValues),
  });

  React.useEffect(() => {
    form.reset(normalizeDefaultValues(defaultValues));
  }, [defaultValues, form]);

  const handleSubmit = form.handleSubmit((values) => {
    const payload = {
      ...values,
      sortOrder:
        typeof values.sortOrder === 'number'
          ? values.sortOrder
          : Number(values.sortOrder || 0),
    };
    onSubmit?.(payload);
  });

  return (
    <Form {...form}>
      <form className="space-y-5" onSubmit={handleSubmit}>
        <div className="grid gap-5 md:grid-cols-2">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>权限标识</FormLabel>
                <FormControl>
                  <Input
                    placeholder="如 user:list"
                    disabled={disableName || mode === 'edit'}
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="displayName"
            render={({ field }) => (
              <FormItem>
                <FormLabel>权限名称</FormLabel>
                <FormControl>
                  <Input placeholder="如 用户列表" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <div className="grid gap-5 md:grid-cols-3">
          <FormField
            control={form.control}
            name="resource"
            render={({ field }) => (
              <FormItem>
                <FormLabel>所属模块</FormLabel>
                <FormControl>
                  <Input placeholder="如 user、document" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="action"
            render={({ field }) => (
              <FormItem>
                <FormLabel>动作类型</FormLabel>
                <FormControl>
                  <Input placeholder="如 list、create、update" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="category"
            render={({ field }) => (
              <FormItem>
                <FormLabel>分类（可选）</FormLabel>
                <FormControl>
                  <Input placeholder="如 文档管理" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <FormField
          control={form.control}
          name="sortOrder"
          render={({ field }) => (
            <FormItem>
              <FormLabel>排序值</FormLabel>
              <FormControl>
                <Input
                  type="number"
                  placeholder="默认 0"
                  {...field}
                  value={field.value ?? 0}
                  onChange={(event) =>
                    field.onChange(Number(event.target.value))
                  }
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>描述</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="补充说明权限作用、使用场景等内容"
                  rows={3}
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="flex flex-col-reverse gap-2 pt-2 sm:flex-row sm:justify-end">
          <Button
            type="button"
            variant="outline"
            disabled={isSubmitting}
            onClick={onCancel}
          >
            取消
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            {isSubmitting
              ? '提交中…'
              : mode === 'create'
              ? '创建权限'
              : '保存变更'}
          </Button>
        </div>
      </form>
    </Form>
  );
}

export { PermissionForm };


